package com.denlaku.longan.handlers;

import com.denlaku.longan.util.JsonUtil;
import com.denlaku.longan.vo.DataSet;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * @author tianx
 */
public class DataSetTypeHandler extends BaseTypeHandler<DataSet> {

	@Override
	public void setNonNullParameter(PreparedStatement ps, int i, DataSet dataSet, JdbcType jdbcType)
			throws SQLException {
		if (dataSet != null) {
			ps.setObject(i, JsonUtil.toJsonString(dataSet));
		}
	}

	@Override
	public DataSet getNullableResult(ResultSet rs, String columnName) throws SQLException {
		String json = rs.getString(columnName);
		return parseObject(json);
	}

	@Override
	public DataSet getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
		String json = rs.getString(columnIndex);
		return parseObject(json);
	}

	@Override
	public DataSet getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
		String json = cs.getString(columnIndex);
		return parseObject(json);
	}
	
	private DataSet parseObject(String json) {
		if (StringUtils.isNotEmpty(json)) {
			return JsonUtil.parseObject(json, DataSet.class);
		}
		return null;
	}

}
